package com.jier.controller;

import com.jier.common.Page;
import com.jier.model.PageParam;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * 基础控制层
 *
 * @author jie_r
 * @date 2016/11/27
 */
public class BaseController {
    /**
     * 返回200状态
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> ResponseEntity<T> ok(T data) {
        return new ResponseEntity<T>(data, HttpStatus.OK);
    }

    /**
     * 返回201状态
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> ResponseEntity<T> created(T data) {
        return new ResponseEntity<T>(data, HttpStatus.CREATED);
    }

    /**
     * 返回204状态
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> ResponseEntity<T> noContent(T data) {
        return new ResponseEntity<T>(data, HttpStatus.NO_CONTENT);
    }

    /**
     * 自定义返回状态
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> ResponseEntity<T> status(T data, HttpStatus status) {
        return new ResponseEntity<T>(data, status);
    }

    /**
     * 下载
     *
     * @param bytes
     * @param fileName
     * @param res
     * @throws IOException
     */
    public void export(byte[] bytes, String fileName, HttpServletResponse res) throws IOException {
        if (bytes.length > 0) {
            res.reset();
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            res.setContentLength(bytes.length);
            OutputStream outputStream = new BufferedOutputStream(res.getOutputStream());
            try {
                outputStream.write(bytes);
            } catch (IOException ex) {
                System.out.println("异常了");
            }
        } else {
            res.setCharacterEncoding("UTF-8");
            res.setContentType("application/json;charset=utf-8");
            res.setStatus(200);
            PrintWriter printWriter = res.getWriter();
            printWriter.println("{\"code\": -1, \"message\": \"没有相关数据！\"}");
            printWriter.close();
        }
    }

    /**
     * 获取Page对象
     *
     * @param pageParam
     * @return
     */
    public Page getPage(PageParam pageParam) {
        return new Page(pageParam.getCurPage(), pageParam.getPageSize());
    }
}
